import AMapLoader from '@amap/amap-jsapi-loader'
import { ILayer, LineLayer, PolygonLayer, Scene } from '@antv/l7'
import { GaodeMap } from '@antv/l7-maps'
import { useEffect, useState } from 'react'

import chartJson from './chartJson.json'
import geoJson from './geojson.json'
import styles from './styles.module.less'

const Test = () => {
  const [scene, setScene] = useState<Scene>()
  const [baseHeight, setBaseHeight] = useState<number>(0)
  const [diffHeight, setDiffHeight] = useState<number>(10000)
  const [lineUp, setLineUp] = useState<ILayer>()
  const [provincelayer, setProvincelayer] = useState<ILayer>()
  const [AMap, setAMap] = useState<any>()
  const [map, setMap] = useState<any>()

  useEffect(() => {
    ;(window as any)._AMapSecurityConfig = {
      securityJsCode: '741205572eee72c70e1ddffac846abcf'
    }

    AMapLoader.load({
      key: 'eb3d2700ca9d788c53538d99f9cb5d85',
      version: '2.0',
      plugins: ['AMap.Geocoder'] //插件列表,
    })
      .then((_AMap) => {
        setAMap(_AMap)
        const map = new _AMap.Map('map', {
          style: 'dark',
          viewMode: '3D',
          center: [120, 29.732983],
          zoom: 8.2,
          pitch: 60,
          token: 'eb3d2700ca9d788c53538d99f9cb5d85'
        })

        setMap(map)
        const s = new Scene({
          id: 'map',
          map: new GaodeMap({
            mapInstance: map
          })
        })
        setScene(s)
      })
      .catch((err) => {
        console.log(err)
      })
  }, [])

  useEffect(() => {
    if (scene && AMap && map) {
      const texts = []

      geoJson.features.map((option) => {
        const { name, center } = option.properties
        const [lng, lat] = center
        texts.push({ name, lng, lat })
        return ''
      })

      const lineDown = new LineLayer()
        .source(geoJson)
        .shape('line')
        .color('#0DCCFF')
        .size(1)
        .style({
          raisingHeight: baseHeight
        })

      const lUp: any = new LineLayer({ zIndex: 1 })
        .source(geoJson)
        .shape('line')
        .color('#0DCCFF')
        .size(2)
        .style({
          // raisingHeight: baseHeight + diffHeight
          raisingHeight: baseHeight
        })

      // lUp.animate({
      //   // enable: true,
      //   // speed: 0.05,
      //   repeat: 0,
      //   duration: 5,
      //   interval: 1,
      //   trailLength: 2,
      //   delay: 0
      // })

      // scene.addLayer(lineDown)
      lineUp?.style({
        raisingHeight: 0
      })
      scene.addLayer(lUp)
      setLineUp(lUp)

      // const lineLayer = new LineLayer()
      //   .source(geoJson)
      //   .shape('wall')
      //   .size(diffHeight)
      //   .style({
      //     heightfixed: true,
      //     opacity: 0.8,
      //     sourceColor: '#0DCCFF',
      //     targetColor: 'rbga(255,255,255, 0)'
      //   })
      // scene.addLayer(lineLayer)

      // const pLayer = new PolygonLayer({})
      //   .source(geoJson)
      //   .size(diffHeight)
      //   .shape('extrude') // fill extrude
      //   // .color('#0DCCFF')
      //   .color('childrenNum', [
      //     '#B8E1FF',
      //     '#7DAAFF',
      //     '#3D76DD',
      //     '#0047A5',
      //     '#001D70'
      //   ])
      //   .active({
      //     color: 'rgb(100,230,255)'
      //   })
      //   .style({
      //     heightfixed: true,
      //     pickLight: true,
      //     raisingHeight: baseHeight,
      //     opacity: {
      //       field: 'childrenNum',
      //       value: [0.2, 0.4, 0.6, 0.8, 1]
      //     }
      //   })

      const pLayer = new PolygonLayer({})
        .source(geoJson)
        .size(diffHeight)
        .shape('fill') // fill extrude
        .color('#0DCCFF')
        .active({
          color: 'rgb(100,230,255)'
        })
        .style({
          heightfixed: true,
          pickLight: true,
          raisingHeight: baseHeight,
          opacity: 1,
          opacityLinear: {
            // 2D 填充图
            enable: true,
            dir: 'out' // in - out
          }
          // sourceColor: 'red',
          // targetColor: 'blue'
        })

      scene.addLayer(pLayer)
      setProvincelayer(pLayer)

      let pLayerLoading = false
      pLayer.on('click', (ev) => {
        if (pLayerLoading) return
        pLayerLoading = true
        try {
          lUp.setData({
            type: 'FeatureCollection',
            features: [ev.feature]
          })
          pLayer.setData({
            type: 'FeatureCollection',
            features: [ev.feature]
          })

          let t = 0
          const d = 0.1
          let base = 8.2
          const interval = setInterval(() => {
            if (t >= 10) {
              clearInterval(interval)
              // scene.setCenter(ev.feature.properties.center)
              pLayerLoading = false
              return
            }
            t++
            base += d
            scene.setZoom(base)
            scene.panTo(ev.feature.properties.center)
          }, 100)

          // const geocoder = new AMap.Geocoder({
          //   radius: 1000, //以已知坐标为中心点，radius为半径，返回范围内兴趣点和道路信息
          //   extensions: 'all' //返回地址描述以及附近兴趣点和道路信息，默认“base”
          // })
          // geocoder.on('complete', (res) => {
          //   console.log(res.regeocode.formattedAddress, 'res')
          // })
          // geocoder.on('error', (error) => {
          //   console.log(error)
          // })
          // geocoder.getAddress(new AMap.LngLat(ev.lngLat.lng, ev.lngLat.lat))
        } catch (err) {
          console.log(err)
        }
      })

      scene.on('click', (ev) => {
        try {
          // 平面地图点击 获取当前经纬度的行政区划
          // console.log(ev.lnglat, 'ev.lngLat')
          // ev.target.getCity((info) => {
          //   console.log('🚀 ~ ev.target.getCity ~ info:', info)
          // })
          // const geocoder = new AMap.Geocoder({
          //   radius: 1000, //以已知坐标为中心点，radius为半径，返回范围内兴趣点和道路信息
          //   extensions: 'all' //返回地址描述以及附近兴趣点和道路信息，默认“base”
          // })
          // geocoder.on('complete', (res) => {
          //   console.log(res, 'res')
          //   console.log(res.regeocode.formattedAddress, 'res')
          // })
          // geocoder.on('error', (error) => {
          //   console.log(error)
          // })
          // geocoder.getAddress(ev.lnglat)
        } catch (err) {
          console.log(err)
        }
      })
    }
  }, [scene, AMap, map])

  const handleClick = () => {
    let height = baseHeight + diffHeight
    let bSize = diffHeight
    let i = 0
    const interval = setInterval(() => {
      console.log(i)

      if (i >= 100) {
        clearInterval(interval)
        return
      }
      height += 200
      bSize += 200
      i++

      lineUp?.style({
        raisingHeight: height
      })
      provincelayer?.size(bSize)
      scene.render()
    }, 16)
  }

  return (
    <div>
      <div id="map" style={{ height: '100vh', width: '100vw' }}></div>
      <div onClick={handleClick} className={styles.btn}>
        按钮
      </div>
    </div>
  )
}

export default Test
